/**
 * 
 */
package com.jysz.certificate.web.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.jysz.certificate.persistence.model.system.Shop;
import com.jysz.certificate.service.system.FinancialService;
import com.jysz.certificate.service.system.ShopService;
import com.jysz.certificate.utils.DateUtil;

/**
 * @author kacarich
 *
 */
@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Namespace("/jr")
public class JasperReportAction extends AbstractJasperReportAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<String> months;
	private String monthFile;
	private String reslutFile;
	@Resource
	private DataSource dataSource;
	private Map<Long, String> shopMap;
	
	/* (non-Javadoc)
	 * @see com.jysz.webcore.ssh.web.struts2.AbstractJasperReportAction#getDataSource()
	 */
	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Action(value="outputMonths_*_*", results={@Result(name = SUCCESS, type="jasper",location= "/jr/{1}.jasper",params={"monthFile", "monthFile", "reslutFile", "reslutFile","documentName","${documentName}","months","months","connection", "connection", "format","{2}","reportParameters","paras","imageServletUrl","/jr/images?image="})})
	public String outputMonths() throws Exception {
		//FIXED:这个location不支持convertion插件呈现视图..有时间重写下让他支持.
		
		this.setConnection(getDataSource().getConnection());
		if(this.getPara()!= null){
			
			String beginDate = getPara().get("STATER_MONTH");
			String endDate = getPara().get("END_MONTH");
			if(StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)){
				setMonths(this.monthList(beginDate, endDate));
				this.setMonthFile("/jr/Departure.jasper");
				this.setReslutFile("/jr/DepartureResult.jasper");
			}
			
			if(this.getParas() == null){
				this.setParas(new HashMap());
			}
			this.getParas().putAll(this.getPara());
		}
        return SUCCESS;
    }

	@Resource
	private ShopService shopService;
	
	@Resource
	private FinancialService financialService;
	
	@Action(value="outputShops_*_*", results={@Result(name = SUCCESS, type="jasper",location= "/jr/{1}.jasper",params={"shopMap", "shopMap", "documentName","${documentName}", "connection", "connection", "format","{2}","reportParameters","paras","imageServletUrl","/jr/images?image="})})
	public String outputShops() throws Exception {
		this.output();
		List<Shop> shops = null;
		if(this.getPara() != null && this.getPara().containsKey("SHOP_ID") && StringUtils.isNotBlank(this.getPara().get("SHOP_ID"))){
			shopMap = new HashMap<Long, String>();
			List<Long> shopIds = new ArrayList<Long>();
			shopIds.add(Long.valueOf(this.getPara().get("SHOP_ID")));
			shops = shopService.findShops(Long.valueOf(this.getPara().get("FINANCIAL_ID")), this.getPara().get("PARAM_DATE"),shopIds);
//			shopMap.put(Long.valueOf(this.getPara().get("SHOP_ID")), this.getPara().get("SHOP_NAME"));
		}else{
			
			shops = shopService.findHaveBusinessShop(Long.valueOf(this.getPara().get("FINANCIAL_ID")), this.getPara().get("PARAM_DATE"), this.getUser());
		}
		
		if(shops == null || shops.size() < 1){
			this.popMessage = "相关店铺不存在数据，导出失败。";
			this.resultBoolean = false;
			setRedirectUrl("/report/bankDayReport.do");
			return "showMsgPage";
		}
		
		shopMap = new HashMap<Long, String>();
		for (Iterator<Shop> iterator = shops.iterator(); iterator.hasNext();) {
			Shop shop = iterator.next();
			shopMap.put(shop.getId(), shop.getShopName());
		}
		
		this.setDocumentName(java.net.URLEncoder.encode(financialService.find(Long.valueOf(this.getPara().get("FINANCIAL_ID"))).getName() + "日报表"+DateUtil.formatDate(DateUtil.getDate(), "yyyyMMdd"),"utf-8"));
		return SUCCESS;
	}
	
	public List<String> getMonths() {
		return months;
	}

	public void setMonths(List<String> months) {
		this.months = months;
	}

	public String getMonthFile() {
		return monthFile;
	}

	public void setMonthFile(String monthFile) {
		this.monthFile = monthFile;
	}
	/**
	 * 获得两月份的区间的月份
	 * @param beginDate
	 * @param endDate
	 * @return
	 * @throws ParseException
	 */
	public List<String> monthList(String beginDate,String endDate){
		List<String> lists = new ArrayList<String>();
		try {
			String[] mons = DateUtil.getBetweenMonthAry(beginDate.substring(0, 7), endDate.substring(0, 7));
			if(mons != null && mons.length>0){
				for(String month : mons){
					lists.add(month);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return lists;
	}

	public String getReslutFile() {
		return reslutFile;
	}

	public void setReslutFile(String reslutFile) {
		this.reslutFile = reslutFile;
	}

	public Map<Long, String> getShopMap() {
		return shopMap;
	}

	public void setShopMap(Map<Long, String> shopMap) {
		this.shopMap = shopMap;
	}
	
	
	private String popMessage = null; // 标准提示信息
	private boolean resultBoolean = true; // 成功失败标志
	private String redirectUrl;

	public String getPopMessage() {
		return popMessage;
	}

	public void setPopMessage(String popMessage) {
		this.popMessage = popMessage;
	}

	public boolean isResultBoolean() {
		return resultBoolean;
	}

	public void setResultBoolean(boolean resultBoolean) {
		this.resultBoolean = resultBoolean;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}
	
	
}
